<template>
  <a-modal :open="open" width="1050px" title="眼科手术预约" destroy-on-close centered @cancel="onCancel">
    <div class="flex">
      <div class="w-2/5 pr-2">
        <SelectTable
          v-model:value="formState.brName"
          type="患者"
          placeholder="姓名/助记码/卡号/手机号/证件号码"
          :disabled="rowData.brId"
          :maxlength="20"
          empty-close
          @select="onSelectPatient"
        />
        <UserCard :user-data="userInfo" class="mt-3">
          <div class="flex flex-col justify-between px-5">
            <div class="flex justify-between items-center mt-2">
              <LabelValue label-align="right" :label-width="120" label="负责人" :value="userInfo.brFzrName" />
              <LabelValue label-align="right" :label-width="120" label="咨询师" :value="userInfo.brZxsName" />
              <LabelValue label-align="right" :label-width="120" label="业务员" :value="userInfo.brYwyName" />
            </div>
            <a-descriptions class="mt-3" :column="1">
              <a-descriptions-item label="关注项目" class="w-full pb-5">
                <a-select
                  v-model:value="formState.brZlxm"
                  :disabled="userInfo.brZlxm"
                  class="w-full"
                  placeholder="请选择"
                  :options="interestProject"
                  allow-clear
                  mode="multiple"
                  max-tag-count="responsive"
                  @change="onChangeSelect"
                />
              </a-descriptions-item>
              <a-descriptions-item label="客户来源" class="w-full">
                <SelectCustomerSource v-model:value="formState.brly" class="w-full" @change="onChangeSelect" />
              </a-descriptions-item>
            </a-descriptions>
            <a-form-item class="w-full">
              <div v-if="tagsList.length > 0" class="flex flex-wrap">
                <div v-for="item in tagsList" :key="item.id" class="tag-item flex items-center mb-2">
                  <div class="tag-item-label truncate max-w-[160px]">{{ item.labelName }}</div>
                  <div class="tag-item-value truncate max-w-[160px]">{{ item.itemNameString }}</div>
                </div>
                <div>
                  <a-button @click="openTagsModal = true"><FormOutlined /></a-button>
                </div>
              </div>
              <a-button v-else type="primary" ghost :disabled="!userInfo.brId" @click="openTagsModal = true">添加标签</a-button>
            </a-form-item>
          </div>
        </UserCard>
      </div>
      <div class="w-3/5">
        <a-form :model="formState" class="form-style-flex">
          <a-form-item v-if="regionList.length !== 1" label="手术院区" class="w-full">
            <a-select
              v-model:value="formState.destOrgCode"
              :options="regionList"
              allow-clear
              :field-names="{ label: 'orgName', value: 'orgCode' }"
              placeholder="请选择"
            />
          </a-form-item>
          <a-form-item label="手术日期" v-bind="validateInfos.aptmOprDate" class="w-1/2">
            <a-date-picker v-model:value="formState.aptmOprDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @keydown.enter="onDateEnter" />
          </a-form-item>
          <a-form-item label="手术时间" class="w-1/2">
            <a-time-picker v-model:value="formState.aptmOprTime" value-format="HH:mm" format="HH:mm" @keydown.enter="onTimeEnter" />
          </a-form-item>
          <a-form-item label="右眼手术" class="w-full">
            <!-- :select-only-one="formState.brId && !formState.isSelectedOd" -->
            <SelectTable
              key="右眼手术"
              v-model:value="formState.odmc"
              type="手术收费项目"
              :search-params="{ brId: formState.brId, bw: '右眼', jklb: '5' }"
              no-page
              auto-mark
              allow-clear
              @select="onSelectOd"
            />
          </a-form-item>
          <!-- <a-form-item label="" class="w-1/2">
            <span class="pl-4"> 标准金额：￥{{ formatAmount(formState.rightBzzje || 0) }}</span>
            <span class="pl-4"> 实际金额：￥{{ formatAmount(formState.rightSjje || 0) }}</span>
          </a-form-item> -->
          <a-form-item label="左眼手术" class="w-full">
            <!-- <SelectTable v-model:value="formState.osIcd9MC" type="手术" @select="onSelectOperation($event, 'osIcd9')" /> -->
            <!-- :select-only-one="formState.brId && !formState.isSelectedOs" -->
            <SelectTable
              key="左眼手术"
              v-model:value="formState.osmc"
              type="手术收费项目"
              :search-params="{ brId: formState.brId, bw: '左眼', jklb: '5' }"
              no-page
              auto-mark
              allow-clear
              @select="onSelectOs"
            />
          </a-form-item>
          <!-- <a-form-item label="" class="w-1/2">
            <span class="pl-4"> 标准金额：￥{{ formatAmount(formState.leftBzzje || 0) }}</span>
            <span class="pl-4"> 实际金额：￥{{ formatAmount(formState.leftSjje || 0) }}</span>
          </a-form-item> -->
          <a-form-item label="手术医生" v-bind="validateInfos.ssys" class="w-full">
            <SelectTable v-model:value="formState.ssys" type="医生" custom-input empty-close @select="onSelectEmp" />
          </a-form-item>
          <!-- <a-form-item label="押金用途" class="w-full">
              <a-select
                v-model:value="formState.zzys"
                :options="depositDoctor"
                placeholder="请选择"
                :field-names="{ label: 'pathName', value: 'id' }"
                @focus="getExpressMode"
                @change="onChangexpressMode"
              />
            </a-form-item> -->
          <a-form-item label="备注" class="w-full">
            <a-textarea v-model:value="formState.memo" :rows="6" placeholder="请输入" />
          </a-form-item>
        </a-form>
      </div>
    </div>
    <template #footer>
      <div class="flex justify-between">
        <div class="pl-[40%]">
          <span> 标准金额：￥{{ formatAmount((formState.leftBzzje || 0) + (formState.rightBzzje || 0)) }}</span>
          <span class="pl-4"> 已缴金额：￥{{ formatAmount((formState.leftSjje || 0) + (formState.rightSjje || 0)) }}</span>
        </div>
        <div>
          <a-button @click="onCancel()">取消</a-button>
          <a-button type="primary" :disabled="!isCompleted" @click="onOk">保存</a-button>
        </div>
      </div>
    </template>
    <TagsModal v-model:open="openTagsModal" :tag-data="tagsList" @success="onSelectTags" />
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { FormOutlined } from '@ant-design/icons-vue'
import { groupBy } from 'lodash-es'
import dayjs from 'dayjs'
import { post } from '@/utils/request'
import { formatAmount } from '@/utils/format'
import SelectTable from '@/components/SelectTable'
// import LabelValue from '@/components/LabelValue'
import UserCard from '@/components/UserCard'
import TagsModal from '@/components/business/TagsModal'
// import { getSystemConfig } from '@/utils/systemConfig'
import appStore from '@/store/app'

const { ORG_CODE } = appStore()

const userInfo = ref({})
const emit = defineEmits(['update:open', 'success'])
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  }
})
// const isEye = ref(true)
const openTagsModal = ref(false)
const formState = ref({
  destOrgCode: ORG_CODE,
  visitOrgCode: ORG_CODE,
  aptmOprDate: '',
  aptmOprTime: '',
  ssys: '',
  aptmOdOprBhName: '',
  aptmOsOprBh: '',
  aptmOsOprBhName: '',
  aptmOdOprBh: '',
  brId: '',
  brName: '',
  brXb: '',
  brAge: ''
})

const interestProject = ref([])
const rulesState = ref({
  aptmOprDate: [{ required: true, message: '请选择手术日期' }],
  // aptmOprTime: [{ required: true, message: '请选择手术时间' }],
  ssys: [{ required: true, message: '请选择手术医生' }]
})
const onSelectEmp = (select) => {
  formState.value = {
    ...formState.value,
    aptmOprEmpId: select.empId,
    ssys: select.empName
  }
}

//获取标签
const tagsList = ref([])
const { resetFields, isCompleted, validateInfos } = useForm(formState, rulesState)

const onSelectPatient = async (select) => {
  //选择下拉表
  formState.value = {
    ...formState.value,
    ...select,
    brNames: select.brName
  }
  userInfo.value = {
    ...select
  }
  !select.brZlxm && (formState.value.brZlxm = [])
  !select.brly && (formState.value.brly = null)
  getTagsList()
}
const onSelectOs = async (select) => {
  formState.value = {
    ...formState.value,
    isSelectedOs: true,
    osmc: select.mc,
    osAdvId: select.id,
    aptmOsOprBh: select?.bh || select?.sfxmbh || '',
    leftBzzje: select.bzzje,
    leftSjje: select.sjje
  }
}
const onSelectOd = async (select) => {
  formState.value = {
    ...formState.value,
    isSelectedOd: true,
    odmc: select.mc,
    odAdvId: select.id,
    aptmOdOprBh: select?.bh || select?.sfxmbh || '',
    rightBzzje: select.bzzje,
    rightSjje: select.sjje
  }
}
//获取标签
const getTagsList = async () => {
  const { code, data, msg } = await post('/common/label/getLableListByPatientld', { brId: userInfo.value.brId })
  if (code !== 0) return message.error(msg || '获取标签失败')
  tagsList.value = groupsList(data, 'labelId')
  userInfo.value.labelList = data.map((tag) => tag.itemId)
}
const groupsList = (list) => {
  const groupedByLabelId = groupBy(list, 'labelId')
  const result = []
  for (const labelId in groupedByLabelId) {
    const items = groupedByLabelId[labelId]
    result.push({
      labelId,
      labelName: items[0].labelName,
      itemId: items.map((item) => item.itemId),
      itemName: items.map((item) => item.itemName),
      itemNameString: items.map((item) => item.itemName).join(', ')
    })
  }
  return result
}
const onSelectTags = async (tags = []) => {
  userInfo.value.labelList = tags.map((tag) => tag.id)
  tagsList.value = groupsList(tags)
  const res = await post('/operation/opex/doAddLabelList', { brId: userInfo.value.brId, labelList: userInfo.value.labelList })
  if (res.code !== 0) return message.error(res.msg || '获取数据失败')
}
const getInterestProject = async () => {
  const { data, code, msg } = await post('/operation/opex/getDictFocusItemList', { zjm: '' })
  if (code !== 0) return message.error(msg || '获取数据失败')
  interestProject.value = data.map((item) => {
    return {
      label: item.itemName,
      value: item.id
    }
  })
}
const onChangeSelect = async () => {
  if (formState.value.brName) {
    formState.value.jksy = 0
    delete formState.value.brAge
    const res = await post('/common/patient/savePatientInfo', formState.value)
    if (res.code !== 0) return message.error(res.msg || '失败')
  }
}
const regionList = ref([])
const getRegionList = async () => {
  const res = await post('/common/emp/getSystemOrganizationList')
  if (res.code !== 0) return message.error(res.msg)
  regionList.value = res.data
}
// :disabled-date="disabledDate"
// const disabledDate = (current) => {
//   // 禁用今天之前的日期
//   return current && current < new Date(new Date().toDateString())
// }
const onOk = async () => {
  if (!formState.value.brName) return message.error('姓名不能为空')
  const res = await post('/operation/opex/doAppointment', formState.value, { loading: true })
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg)
  emit('success')
  onCancel()
  // if (!formState.value.aptmOsOprBh && !formState.value.aptmOdOprBh) return message.error('必须选择一种手术')
  // if (props.rowData?.aptmLsh) {
  //   onRequest()
  // } else {
  //   getAppointment()
  // }
}

// const getAppointment = async () => {
//   const res = await post('/operation/opex/chekDoAppointment', { brId: formState.value.brId })
//   if (res.code !== 0) return message.error(res.msg)
//   if (res.data) {
//     const isConfirm = await cofirmModal({ title: '提示', content: res.data })
//     if (isConfirm) {
//       onRequest()
//     }
//   } else {
//     onRequest()
//   }
// }

// const onRequest = async () => {}

const onCancel = () => {
  emit('update:open', false)
  resetFields()
}
const getUserInfo = async (brId) => {
  //获取病人信息
  const { code, data, msg } = await post('/outp/mzdj/getPatientInfoList', { brId, pageNum: 1, pageSize: 10 })
  if (code !== 0) return message.error(msg)
  userInfo.value = {
    ...data[0]
  }
}

watch(
  () => props.open,
  (val) => {
    if (val) {
      resetFields()
      getRegionList()
      getInterestProject()
      if (props.rowData?.brId) {
        formState.value = { destOrgCode: ORG_CODE, visitOrgCode: ORG_CODE, ...props.rowData }
        formState.value.brZlxm = formState.value.brZlxm || []
        formState.value.brly = formState.value.brly || undefined
        getUserInfo(props.rowData?.brId)
        userInfo.value.brId = props.rowData?.brId
        getTagsList()
      } else {
        userInfo.value = {}
        formState.value = { destOrgCode: ORG_CODE, visitOrgCode: ORG_CODE }
        tagsList.value = []
      }
      // isEye.value = getSystemConfig('OO_OPERATION_REGISTER_CHOOSE_MODE') === '1' // 手术0：处置1：全部手术
    }
  }
)
watch(
  () => formState.value.osmc,
  (val) => {
    if (!val) {
      formState.value.aptmOsOprBh = ''
    }
  }
)
watch(
  () => formState.value.odmc,
  (val) => {
    if (!val) {
      formState.value.aptmOdOprBh = ''
    }
  }
)
const onDateEnter = (e) => {
  const dateString = e.target.value
  const regex1 = /^\d{8}$/ // 匹配YYYYMMDD格式
  const regex2 = /^\d{4}-\d{2}-\d{2}$/ // 匹配YYYY-MM-DD格式
  const regex3 = /^\d{4}\/\d{2}\/\d{2}$/ // 匹配YYYY/MM/DD格式
  const regex4 = /^\d{4}\.\d{2}\.\d{2}$/ // 匹配YYYY.MM.DD格式
  // 检查日期字符串是否符合任何一个正则表达式
  const isValidDate = regex1.test(dateString) || regex2.test(dateString) || regex3.test(dateString) || regex4.test(dateString)
  if (isValidDate) {
    formState.value.aptmOprDate = dayjs(dateString).format('YYYY-MM-DD')
    e.target.blur()
  }
}
const onTimeEnter = (e) => {
  const timeString = e.target.value
  const regex1 = /^\d{4}$/ // 匹配HHmm格式
  const isValidTime = regex1.test(timeString)
  if (isValidTime) {
    //HHmm to HH:mm
    formState.value.aptmOprTime = dayjs(timeString, 'HHmm').format('HH:mm')
    e.target.blur()
  }
}
</script>

<style lang="less" scoped>
.ant-descriptions {
  :deep(.ant-descriptions-item-label) {
    padding-top: 3px;
  }
}
.tag-item {
  margin-right: 8px;
  overflow: hidden;
  border: 1px solid var(--primary-color);
  border-radius: 8px;
  .tag-item-label {
    padding: 4px 12px;
    color: #fff;
    background-color: var(--primary-color);
  }
  .tag-item-value {
    padding: 4px 12px;
  }
}
.ant-tag-checkable-checked {
  color: #fff;
  background-color: var(--primary-color);
}
</style>
